package com.logicalthinking.socialmall.service.impl;

import com.github.chenlijia1111.commonModule.service.CommonModuleShopServiceI;
import com.github.chenlijia1111.commonModule.service.CommonModuleUserServiceI;
import com.github.chenlijia1111.commonModule.utils.SpringUtil;
import com.github.chenlijia1111.utils.common.Result;
import com.github.chenlijia1111.utils.core.PropertyCheckUtil;
import com.github.chenlijia1111.utils.core.StringUtils;
import com.github.chenlijia1111.utils.list.Lists;
import com.github.chenlijia1111.utils.oauth.jwt.JWTUtil;
import com.logicalthinking.socialmall.common.enums.UserSourceEnum;
import com.logicalthinking.socialmall.common.pojo.Constants;
import com.logicalthinking.socialmall.common.vo.requestVo.clientUser.ClientListQueryParams;
import com.logicalthinking.socialmall.common.vo.responseVo.clientUser.ClientUserListVo;
import com.logicalthinking.socialmall.dao.ClientAuthenticateSelfMapper;
import com.logicalthinking.socialmall.dao.ClientAuthenticateShopMapper;
import com.logicalthinking.socialmall.dao.ClientUserMapper;
import com.logicalthinking.socialmall.dao.ThirdPartyUsersMapper;
import com.logicalthinking.socialmall.entity.ClientAuthenticateSelf;
import com.logicalthinking.socialmall.entity.ClientAuthenticateShop;
import com.logicalthinking.socialmall.entity.ClientUser;
import com.logicalthinking.socialmall.entity.ThirdPartyUsers;
import com.logicalthinking.socialmall.service.ClientUserServiceI;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 客户端用户
 *
 * @author chenLiJia
 * @since 2020-02-17 14:43:59
 **/
@Service
public class ClientUserServiceImpl implements ClientUserServiceI, CommonModuleShopServiceI, CommonModuleUserServiceI {


    @Resource
    private ClientUserMapper clientUserMapper;
    @Resource
    private ClientAuthenticateSelfMapper clientAuthenticateSelfMapper;//个人认证
    @Resource
    private ClientAuthenticateShopMapper clientAuthenticateShopMapper;//商家认证
    @Resource
    private ThirdPartyUsersMapper thirdPartyUsersMapper;//第三方信息


    /**
     * 添加
     *
     * @param params 添加参数
     * @return com.github.chenlijia1111.utils.common.Result
     * @author chenLiJia
     * @since 2020-02-17 14:43:59
     **/
    @Override
    public Result add(ClientUser params) {

        int i = clientUserMapper.insertSelective(params);
        return i > 0 ? Result.success("操作成功") : Result.failure("操作失败");
    }

    /**
     * 编辑
     *
     * @param params 编辑参数
     * @return com.github.chenlijia1111.utils.common.Result
     * @author chenLiJia
     * @since 2020-02-17 14:43:59
     **/
    @Override
    public Result update(ClientUser params) {

        int i = clientUserMapper.updateByPrimaryKeySelective(params);
        return i > 0 ? Result.success("操作成功") : Result.failure("操作失败");
    }

    /**
     * 通过id查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public ClientUser findById(Integer id) {
        if (Objects.nonNull(id)) {
            return clientUserMapper.selectByPrimaryKey(id);
        }
        return null;
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     */
    @Override
    public List<ClientUserListVo> listPage(ClientListQueryParams params) {
        List<ClientUserListVo> list = clientUserMapper.listPage(params);
        getFullInfo(list);
        return list;
    }

    /**
     * 关联查询用户列表信息
     *
     * @param list
     */
    @Override
    public void getFullInfo(List<? extends ClientUserListVo> list) {
        if (Lists.isNotEmpty(list)) {
            //查询认证信息
            Set<Integer> userIdSet = list.stream().map(e -> e.getId()).collect(Collectors.toSet());
            List<ClientAuthenticateSelf> clientAuthenticateSelves = clientAuthenticateSelfMapper.listByUserIdSet(userIdSet);
            List<ClientAuthenticateShop> clientAuthenticateShops = clientAuthenticateShopMapper.listByUserIdSet(userIdSet);
            List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersMapper.listByUserIdSetAndType(userIdSet, UserSourceEnum.WECHAT.getSource());

            //开始关联
            for (ClientUserListVo vo : list) {
                //身份证号码
                //先查商家认证的,商家没认证再查询个人认证的信息
                Optional<ClientAuthenticateShop> any = clientAuthenticateShops.stream().filter(e -> Objects.equals(e.getUserId(), vo.getId())).findAny();
                if (any.isPresent()) {
                    ClientAuthenticateShop clientAuthenticateShop = any.get();
                    vo.setIdCard(clientAuthenticateShop.getIdCard());
                    vo.setClientAddressName(clientAuthenticateShop.getBusinessAddress());
                } else {
                    //查询
                    Optional<ClientAuthenticateSelf> any1 = clientAuthenticateSelves.stream().filter(e -> Objects.equals(e.getUserId(), vo.getId())).findAny();
                    if (any1.isPresent()) {
                        ClientAuthenticateSelf clientAuthenticateSelf = any1.get();
                        vo.setIdCard(clientAuthenticateSelf.getIdCard());
                    }
                }

                //第三方信息查询昵称
                Optional<ThirdPartyUsers> any1 = thirdPartyUsers.stream().filter(e -> Objects.equals(e.getClientUserId(), vo.getId())).findAny();
                if (any1.isPresent()) {
                    ThirdPartyUsers thirdPartyUsers1 = any1.get();
                    vo.setNickName(thirdPartyUsers1.getNickname());
                }
            }
        }
    }

    @Override
    public Optional<ClientUser> currentUser() {
        HttpServletRequest request = SpringUtil.getCurrentRequest();
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.isNotEmpty(token)) {
            //解析token
            try {
                Claims claims = JWTUtil.parseJWT(token, Constants.JWT_SIGN_KEY);
                String id = claims.getId();
                if (StringUtils.isInt(id)) {
                    ClientUser clientUser = clientUserMapper.selectByPrimaryKey(Integer.valueOf(id));
                    return Optional.ofNullable(clientUser);
                }
            } catch (Exception e) {
                e.printStackTrace();
                //如果抛出异常,解析失败
            }

        }
        //测试情况,先全部都是1
        ClientUser clientUser = clientUserMapper.selectByPrimaryKey(1);
        return Optional.ofNullable(clientUser);
    }

    /**
     * 条件查询
     *
     * @param condition
     * @return
     * @author chenLiJia
     * @since 2020-02-17 14:43:59
     **/
    @Override
    public List<ClientUser> listByCondition(ClientUser condition) {

        PropertyCheckUtil.transferObjectNotNull(condition, true);
        return clientUserMapper.select(condition);
    }

    /**
     * 获取当前商家id
     *
     * @return
     */
    @Override
    public String currentShopId() {
        Optional<ClientUser> optional = currentUser();
        if (optional.isPresent()) {
            ClientUser clientUser = optional.get();
            return String.valueOf(clientUser.getId());
        }
        return null;
    }

    /**
     * 获取当前用户id
     *
     * @return
     */
    @Override
    public String currentUserId() {
        Optional<ClientUser> optional = currentUser();
        if (optional.isPresent()) {
            ClientUser clientUser = optional.get();
            return String.valueOf(clientUser.getId());
        }
        return null;
    }
}
